package com.yyaccp.hncc.oss.aliyun;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 *
 * @author 天天向上 （john.yi@qq.com）
 * @date 2020/8/18
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OssServiceImpl implements OssService {
    private final OSS ossClient;
    private final OssConfig ossConfig;

    @Override
    public Map<String, Object> upload(String originalFilename, InputStream in) {
        Map<String, Object> result = new HashMap<>();
        String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        PutObjectResult putObjectResult = ossClient.putObject(ossConfig.getBucketName(), ossConfig.getDirPrefix() + filename, in);
        result.put("originalFilename", originalFilename);
        result.put("filename", filename);
        result.put("message", "success");
        result.put("etag", putObjectResult.getETag());
        return result;
    }

    @Override
    public Map<String, Object> download(String filename, OutputStream outputStream) {
        OSSObject ossObject = ossClient.getObject(ossConfig.getBucketName(), ossConfig.getDirPrefix() + filename);
        HashMap<String, Object> result = new HashMap<>();
        try (InputStream inputStream = ossObject.getObjectContent()){
            FileCopyUtils.copy(inputStream, outputStream);
            result.put("result", "success");
        } catch (IOException e) {
            log.error("下载文件失败{}", filename, e);
            result.put("result", "error");
        }
        return result;
    }


    @Override
    public Map<String, String> policy() {
        return null;
    }

    @Override
    public Map<String, String> callback(HttpServletRequest request) {
        return null;
    }
}
